package com.bole.controller;

import com.bole.data.Result;
import com.bole.dto.collections.CollectionsDto;
import com.bole.pojo.CollectionsDo;
import com.bole.pojo.TbCarDo;
import com.bole.service.CarService;
import com.bole.service.CollectionsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("collections")
public class CollectionsController {

    @Resource
    private CollectionsService collectionsService;

    @Resource
    private CarService carService;

    /**
     * 保存收藏
     * @param collectionsDto
     * @return
     */
    @PostMapping
    public Result saveCollections(@RequestBody CollectionsDto collectionsDto) {
        try {
            collectionsService.saveCollections(collectionsDto);
            return Result.ok().setData("保存收藏成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail().setData("保存收藏失败");
        }
    }

    /**
     * 判断是否收藏
     * @param carId
     * @param userId
     * @return
     */
    @GetMapping("/{carId}/{userId}")
    public Result isCollection(@PathVariable("carId") Long carId,
                               @PathVariable("userId") Long userId) {
        try {
            boolean isCollection = collectionsService.isCollection(carId,userId);

            return Result.ok().setData(isCollection);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail().setData("系统错误");
        }
    }

    /**
     * 获取收藏
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    public Result findCollection(@PathVariable("userId") Long userId) {
        try {
            List<CollectionsDo> collection = collectionsService.findCollection(userId);
            List<TbCarDo> carDoList = carService.findCarByCarId(collection);
            return Result.ok().setData(carDoList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail().setData("查询错误");
        }
    }

    @DeleteMapping("/{carId}/{userId}")
    public Result deleteCollections(@PathVariable("carId") Long carId,
                                    @PathVariable("userId") Long userId) {
        try {
            collectionsService.deleteCollections(carId,userId);
            return Result.ok().setData("取消成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail().setData("取消收藏失败");
        }
    }
}
